package com.w3coffee.web.control;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.w3coffee.web.User;

public abstract class BaseController implements Controller {

	public ModelAndView adaptive(HttpServletRequest req,
			HttpServletResponse resp, String base, Map<String, ?> model) {
//		Enumeration<?> names = req.getHeaderNames();
//		while (names.hasMoreElements()) {
//			String name = names.nextElement().toString();
//			System.out.println("#header# " + name + " : " + req.getHeader(name));
//		}
		
		resp.setContentType("text/html");
		resp.setCharacterEncoding("UTF-8");
		return new ModelAndView(base, model);
	}

	public Object getBean(String name) {
		return ContextServlet.getBean(name);
	}

	private static StringBuffer baseUrl = null;

	public synchronized String getBaseUrl(HttpServletRequest req) {
		if (baseUrl == null) {
			baseUrl = new StringBuffer();
			if ((req.getServerPort() == 80) || (req.getServerPort() == 443)) {
				baseUrl.append(req.getScheme()).append("://")
						.append(req.getServerName())
						.append(req.getContextPath());
			} else {
				baseUrl.append(req.getScheme()).append("://")
						.append(req.getServerName()).append(':')
						.append(req.getServerPort())
						.append(req.getContextPath());
			}
		}

		return baseUrl.toString();
	}
	
	public Map<String, Object> getDefaultModel(HttpServletRequest req) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("baseUrl", getBaseUrl(req));
		model.put("news", ContextServlet.getNews());
		
		try {
			CheckinToken ct = (CheckinToken) req.getSession(false).getAttribute("TOKEN");
			User user = ct.getUser();
			if (user != null) {
				if (user.isValid()) {
					model.put("user", user);
				}
			}
		} catch (Exception e) {
			
		}
		
		return model;
	}
}
